using System;
using System.Collections;
using System.Reflection;
using System.Text;
using System.Xml;
using InfoJetSoft.Service.Entity;
using InfoJetSoft.Service.Util;
using InfoJetSoft.Service.ManagedCode;

namespace InfoJetSoft.Service.Worker
{
	/// <summary>
	/// Summary description for ManagedCodeOnMergeRequestWorker.
	/// </summary>
	class ManagedCodeOnMergeRequestWorker
	{
		
		public static void OnMergeRequest(Form form, ArrayList xmlList)
		{
			if( form.Manifest.ManagedAssembly == null || form.Manifest.ManagedAssembly.ModelType == null )
			{
				return;
			}

			ManagedCodeUtil.createModel( form );
			object model = form.ManagedCodeModel;

			MethodInfo onMergeRequest = ManagedCodeUtil.findMethod( model, Microsoft.Office.Interop.InfoPath.SemiTrust.InfoPathEventType.OnMergeRequest );
			if( onMergeRequest == null )
			{
				return;
			}

			XDocument xdoc = new XDocument( form );
			Application app = new Application( form );

			try
			{
				MethodInfo startup = ManagedCodeUtil.findMethod( model, "_Startup" );
				startup.Invoke( model, new object[]{ app, xdoc } );

				int index = 0;
				foreach(string mergeXml in xmlList)
				{
					XmlDocument xmlDoc = new XmlDocument();
					xmlDoc.LoadXml( mergeXml );
					NamespaceResolver nsResolver = new NamespaceResolver(xmlDoc);

					XMLDocument xDoc = new XMLDocument(form, xmlDoc, nsResolver);

					MergeEvent mergeEvent = new MergeEvent( xdoc, xDoc );
					mergeEvent.Count = xmlList.Count;
					mergeEvent.Index = index;

					onMergeRequest.Invoke( model, new object[]{ mergeEvent } );

					index ++;
				}
			
				MethodInfo shutdown = ManagedCodeUtil.findMethod( model, "_Shutdown" );
				shutdown.Invoke( model, new object[]{} );
			}
			catch( Exception e )
			{
                FormUtil.addInnerExceptionMassage(form, onMergeRequest.Name, e);
			}
		}

	}
}
